package com.zwj.service.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zwj.config.annotaion.Esb;
import com.zwj.mapper.UserMapper;
import com.zwj.service.UserService;
import com.zwj.vo.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zwj
 * @since 2022-05-07
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private UserMapper userMapper;

    /**
     * @param response
     * @throws UnsupportedEncodingException
     */
    @Override
    public void userExport(HttpServletResponse response) throws UnsupportedEncodingException {
        List<User> users = userMapper.selectAllUser();

        //使用工具类创建writer,默认的是xls
        ExcelWriter writer = ExcelUtil.getWriter();
        //自定义别名，给数据字段起一个别名
        writer.addHeaderAlias("id", "编号");
        writer.addHeaderAlias("name", "姓名");
        writer.addHeaderAlias("age", "年龄");
        writer.addHeaderAlias("email", "邮箱");

        //设置标题，并且合并单元格
        writer.merge(4, "用户信息");
        //写入内容
        writer.write(users, true);

        //设置编码不然中文会乱码
        response.setContentType("application/vnd.ms-excel;charset=utf-8");

        //filename=() 设置文件名
        response.setHeader("Content-Disposition", "attachment;filename=" + new String("用户表".getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1) + ".xls");

        //把目标写入流
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            writer.flush(out, true);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭writer，释放内存
            writer.close();
        }
        IoUtil.close(out);
    }

    @Esb
    @Override
    public User testESB(User user) {
        log.error("Service:：{}", user.toString());
        user.setEmail("");
        user.setPassword("");
        return user;
    }
}
